﻿using CatUtils.Utils.Currency;
using CatUtils.Utils.Currency.TextUtils;

using CatUtils.Utils.SpecialUtils.Html;
using CatUtils.Utils.SpecialUtils.View;
using CatUtilsDll.Utils.Currency.TextUtils;
using CatUtilsDll.Utils.Currency.WebUtils;
using RabbitDownload.Helper;
using RabbitDownload.Helper.Currency;

using RabbitDownload.Helper.ViewHelper;
using RabbitDownload.WebSite.WebCurrency;
using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using static RabbitDownload.WebSite.Local.TagManger.LocalTagStatcivalue;

namespace RabbitDownload.WebSite.Zerochan
{
    internal class ZerochanScannerTag
    {
        public void StartWithFile(string FilePath, string StartPage, string EndPage, string ScoreText)
        {
            List<string> TagList = new SiteCurrencyHelper().GetDownoadProcess(FilePath, "//item");

            while (TagList.Count > 0)
            {
                string TagInfo = TagList[0];
                TagList.RemoveAt(0);
                new SiteCurrencyHelper().SaveDownloadProcess(FilePath, TagList);
                TranslateStruct translateStruct = new TranslateStruct(TagInfo);
                if (translateStruct.RomaTag == "" || translateStruct.ZhTag == "") continue;
                Console.WriteLine("扫描标签{0}，罗马音标签{1}", translateStruct.ZhTag, translateStruct.RomaTag);
                StartScanner(translateStruct.RomaTag, StartPage, EndPage, ScoreText, translateStruct.ZhTag + "-");
            }
        }

        /// <summary>
        ///启动扫描，批量任务模式
        /// </summary>
        /// <param name="TagList"></param>
        /// <param name="StartPage"></param>
        /// <param name="EndPage"></param>
        /// <param name="ScoreText"></param>
        /// <param name="Tip"></param>
        public void StartScanner(List<string> TagList, string StartPage, string EndPage, string ScoreText)
        {
            foreach (string Line in TagList)
            {
                if (Line == "")
                    continue;

                StartScanner(Line, StartPage, EndPage, ScoreText);
            }
            MessageHelper.Alert("全部扫描完成！");
        }

        /// <summary>
        /// 启动单个扫描
        /// </summary>
        /// <param name="Tag"></param>
        /// <param name="StartPage"></param>
        /// <param name="EndPage"></param>
        /// <param name="ScoreText"></param>
        /// <param name="Tip"></param>
        public void StartScanner(string Tag, string StartPage, string EndPage, string ScoreText, string Tip = "")
        {
            int StartCount = TextHelper.StringToInt(StartPage);
            int EndCount = TextHelper.StringToInt(EndPage);
            int ScoreCount = TextHelper.StringToInt(ScoreText);
            Console.WriteLine(Tag);
            string API = string.Format("https://www.zerochan.net/{0}?s=fav?p={1}",
                WebHelper.UrlEncode(Tag), "{0}");

            List<string> ImgList = Analysis(API, StartCount, EndCount, ScoreCount);
            SaveHelper.AutoSave(ImgList, "Zerochan", Tip + Tag);
        }

        private List<string> Analysis(string API, int StartCount, int EndCount, int ScoreCount)
        {
            int JumpCount = 3;
            List<string> ImgList = new List<string>();
            for (; EndCount == 0 || StartCount < EndCount; StartCount++)
            {
                string TempAPI = string.Format(API, StartCount);
                Console.WriteLine(TempAPI);
                String Shtml = StaticValueOld.CookiesWebclient.GetHtml(TempAPI, WebHelper.PcWebHeader());
                List<ZerochanInfo> zerochanInfoList = AnalysisHtml(Shtml);
                List<string> TempImglist = new List<string>();

                if (zerochanInfoList.Count == 0)
                {
                    Console.WriteLine("未抓取到内容，距离跳出还有{0}次", --JumpCount);
                    if (JumpCount == 0)
                        break;
                }
                else JumpCount = 3;

                foreach (ZerochanInfo Single in zerochanInfoList)
                {
                    if (Single.Score >= ScoreCount)
                    {
                        TempImglist.Add(Single.Fileurl);
                        Console.WriteLine("暂缓存图片{0}张，图片评分{1}", TempImglist.Count, Single.Score);
                    }
                }

                if (JudeListRepeat(ImgList, TempImglist))
                {
                    Console.WriteLine("出现重复现象，结束扫描。");
                    break;
                }
                else
                {
                    ImgList.AddRange(TempImglist);
                    Console.WriteLine("总缓存{0}张", ImgList.Count);
                }
            }

            return ImgList;
        }

        /// <summary>
        /// 检查是否出现重复，如果完全重复返回true 否则返回false
        /// </summary>
        /// <param name="ImgList"></param>
        /// <param name="TempImglist"></param>
        /// <returns></returns>
        private bool JudeListRepeat(List<string> ImgList, List<string> TempImglist)
        {
            int TemplistCount = TempImglist.Count;

            foreach (string Line in TempImglist)
            {
                if (ImgList.Contains(Line))
                {
                    Console.WriteLine("发现重复" + Line);
                    TemplistCount--;
                }
            }
            if (TemplistCount == 0)
                return true;
            else return false;
        }

        private List<ZerochanInfo> AnalysisHtml(string Shtml)
        {
            List<ZerochanInfo> zerochanInfoList = new List<ZerochanInfo>();

            foreach (string SinglePost in HtmlHelper.GetHtmlValueList(Shtml, "//ul[@id='thumbs2']/li"))
            {
                int ImgScore = TextHelper.StringToInt(
                     HtmlHelper.GetFirstText(SinglePost, "/li/a/span").Replace(" Fav", "")
                    );
                string Imgurl = HtmlHelper.GetFirstSrc(SinglePost, "/li/a/img");
                Imgurl = Imgurl.Replace("s3.zerochan.net", "static.zerochan.net").Replace(".240.", ".full.");

                if (Imgurl != "")
                    zerochanInfoList.Add(new ZerochanInfo { Fileurl = Imgurl, Score = ImgScore });
            }

            return zerochanInfoList;
        }

        private struct ZerochanInfo
        {
            private string fileurl;
            private int score;

            public string Fileurl { get => fileurl; set => fileurl = value; }
            public int Score { get => score; set => score = value; }
        }
    }
}